package net.huafv.authoritycontrol.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.xml.bind.DatatypeConverter;
import java.util.Date;
import java.util.Map;

@Component
public class JwtUtil {

    public static byte[] getSecretByte(String secret){
        return DatatypeConverter.parseBase64Binary(DatatypeConverter.printBase64Binary(secret.getBytes()));
    }

    /**
     * 创建token
     * @param secret
     * @param content
     * @param expire
     * @return
     */
    public static String createToken(String secret, Map<String,Object> content, Date expire){
        return createToken(secret, null, content, expire);
    }

    /**
     * 创建token
     * @param secret
     * @param subject
     * @param content
     * @param expire
     * @return
     */
    public static String createToken(String secret,String subject,Map<String,Object> content,Date expire){
        return Jwts.builder()
                .setSubject(subject)
                .setClaims(content)
                .setExpiration(expire)
                .signWith(SignatureAlgorithm.HS512,getSecretByte(secret))
                .compact();
    }

    /**
     * 拿到摘要信息
     * @param secret
     * @param token
     * @return
     */
    public static Claims getClaims(String secret, String token) {
        try{
            return Jwts.parser().setSigningKey(getSecretByte(secret)).parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            return e.getClaims();
        }catch (Exception e){
            return null;
        }
    }


    /**
     * 查看是否过期失效
     * @param secret
     * @param token
     * @return
     */
    public static boolean isExpire(String secret,String token){
        try{
            Jwts.parser().setSigningKey(getSecretByte(secret)).parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            return true;
        }
        return false;
    }

    /**
     * 根据主题来判断token是否有效
     * @param secret
     * @param token
     * @param subject
     * @return
     */
    public static boolean checkToken(String secret,String token,String subject){
        if (subject==null) {
            return false;
        }
        return subject.equals(getClaims(secret, token).getSubject());
    }

}
